<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午9:25
 */


class SelfOrderService extends ServiceBase {

    public function createOrder($member, $foodIds, $counts, $totalPrice){
        $order = $member->createOrder($foodIds, $counts, $totalPrice);
        if(!$order){
            $this->errors()->merge($member->errors());
            return false;
        }
        return $order;
    }

    public function getPicket($order_id, $checksum, $timestamp){

        $order = Order::find($order_id);
        if(!$this->checkSignature($order, $checksum, $timestamp)){
            return false;
        }

        $result = $order->getPicket();
        if(!$result){
            $this->errors()->merge($order->errors());
            return false;
        }
        return $result;
    }

    public function setOrderStatus($order_id, $checksum, $timestamp, $keyword = Order::GOT_PICKET){
        $order = Order::find($order_id);
        if(!$this->checkSignature($order, $checksum, $timestamp)){
            return false;
        }

        $result = $order->setStatus($keyword);
        if(!$result){
            $this->errors()->merge($order->errors());
            return false;
        }
        return $result;
    }

    public function settle($orderId, $checksum, $timestamp){
        $order = Order::find($orderId);
        if(!$this->checkSignature($order, $checksum, $timestamp)){
            return false;
        }

        $orderService = new OrderService($order);
        //使用积分结算
        if(!$orderService->settle(MemberAccount::SCHOOL_CARD_ACCOUNT)){
            $this->errors()->merge($this->order->member->errors());
            return false;
        }
        return true;
    }

    public function checkSignature($order, $checksum, $timestamp){
        if(!$order){
            $this->errors()->add('error', '错误的订单号');
            return false;
        }
        if(!$order->checkSignature($checksum, $timestamp)){
            $this->errors()->add('error', '验证失败');
            return false;
        }
        return true;
    }

    public function getFoodRankingListForMostOrder($limit){
        return OrderFood::groupBy('name')->select(DB::raw('id, name, sum(count) as total_count'))->orderBy('total_count', 'desc')->limit($limit)->get();
    }

}

